package com.spzx.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spzx.domain.OrderInfo;
import com.spzx.domain.OrderItem;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单Service业务层处理
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    OrderLogMapper orderLogMapper;

    @Override
    public PageInfo<OrderInfo> selectUserOrderInfoList(Integer pageNum, Integer pageSize, Integer orderStatus) {
        // 启动分页，从pageNum页开始，每页显示pageSize条记录
        PageHelper.startPage(pageNum, pageSize);

        List<OrderInfo> orderInfos = orderInfoMapper.selectList(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderStatus, orderStatus));

        List<Long> orderNos = orderInfos.stream().map(OrderInfo::getId).toList();
        // 遍历每个订单ID，查询对应的订单详情项，并将详情项关联到订单信息中
        orderNos.forEach(orderNo -> {
            List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderNo));
            orderInfos.stream().filter(orderInfo -> orderInfo.getId().equals(orderNo)).forEach(orderInfo -> orderInfo.setOrderItemList(orderItemList));
        });

        return new PageInfo<>(orderInfos);
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        // 创建一个订单信息的查询包装器
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        // 如果订单信息存在
        if (orderInfo != null) {
            // 创建一个订单项的查询包装器
            LambdaQueryWrapper<OrderItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<>();
            itemLambdaQueryWrapper.eq(OrderItem::getOrderId, orderInfo.getId());
            List<OrderItem> orderItemList = orderItemMapper.selectList(itemLambdaQueryWrapper);
            // 将订单项列表设置到订单信息对象中
            orderInfo.setOrderItemList(orderItemList);
        }


        return orderInfo;
    }
}
